package br.com.poolme.telas;

import java.io.IOException;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.TextField;
import br.com.poolme.bd.Persistencia;
import br.com.poolme.core.UIController;

public class CadastroRecorde {

	private static CadastroRecorde instancia;
    private Form formCadastroRecorde;
    private TextField campoNome;
    private Command cadastrar, menu;

    private Persistencia persistencia;

    public static CadastroRecorde getInstancia() {
        if (instancia == null) {
            instancia = new CadastroRecorde();
        }
        return instancia;
    }

    public CadastroRecorde() {
        formCadastroRecorde = new Form("Novo Recorde");

        campoNome = new TextField("Nome:", "", 100, TextField.ANY);

        cadastrar = new Command("Cadastrar", Command.OK, 1);
        menu = new Command("Voltar", Command.BACK, 1);
        this.persistencia = new Persistencia();
    }

    public Command getBotaoCadastrar() {
        return cadastrar;
    }

    public Command getBotaoMenu() {
        return menu;
    }

    public Form getFormCadastroRecorde(){
        return formCadastroRecorde;
    }

    public TextField getCampoNome(){
        return campoNome;
    }

    public void construirTela(UIController classe) {
        formCadastroRecorde.append(campoNome);
        formCadastroRecorde.addCommand(cadastrar);
        formCadastroRecorde.addCommand(menu);
        formCadastroRecorde.setCommandListener(classe);
    }

    public void cadastrarRecorde(TextField campoNome, int pontuacao) {
        persistencia.cadastrarRecorde(campoNome.getString(), pontuacao);
    }

    public void listar(UIController classe){
        List lista = new List("Recordes", List.IMPLICIT);
        String[] arString = persistencia.listarRecordesOrdenados();
        if(arString != null && arString.length > 0){
            for(int i=0 ; i<arString.length ; i++){
                if(arString[i] != null){
                    Image img = null;
                    try {
                        img = Image.createImage("/res/F" + i + ".PNG");
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    lista.append(arString[i], img);
                }
            }
        }
        lista.addCommand(menu);
        lista.setCommandListener(classe);
        classe.getTela().setCurrent(lista);
    }

}
